from typing import Optional
from api.mod import ComPortCalculate, ComPortCmd, ComPortMethod, ComPortModel, SerialOption


""" CPET 厂商型号 CP8212 485模块 """
""" 显示表符合标准的MODBUS-RTU通讯协议,支持03H/06H/10H等功能码(十六进制),通讯响应速度<300ms。 """
class CP8212ComPort485Model(ComPortModel):
    def __init__(self,port="",flag="CH340",timeout=0.3):
        if port == "":
            port = self.get_port(flag)
        options = SerialOption(port=port,baudrate=38400,bytesize=8,parity="N",stopbits=1,timeout=timeout)
        cmd = ComPortCmd.Voltage
        method = ComPortMethod.Get
        calculate = ComPortCalculate.ModbusCrc16
        
        super().__init__(options,14,"big",cmd,method,calculate)
    """ 同步命令 """
    def sync_msg(self) ->Optional[str]:
        self.msg = None
        self.divided = 1
        self.unit = ""
        if self.cmd == ComPortCmd.Voltage:
            """ 获取电池电压 """
            if self.method == ComPortMethod.Get:
                self.msg = "01 04 00 02 00 01"
                self.value_range  = (3,5)
                self.divided = 100.0
                self.unit = "V"
        elif self.cmd == ComPortCmd.Current:
            """ 获取电池电流 """
            if self.method == ComPortMethod.Get:
                self.msg = "01 04 00 01 00 01"
                self.value_range  = (3,5)
                self.divided = 100.0
                self.unit = "A"